<?php
/**
 * 数据存储连接管理器
 *
 * @author ananda
 */
class Connection extends Kernel
{
    /**
     * 连接对象集
     * @var <array>
     */
    protected static $connections = array();

    /**
     * 数据类初始化
     */
    public static function init()
    {
        register_shutdown_function('Connection::close');
    }

    /**
     * 获取数据库连接
     * @param <string> $name
     * @return <Connection_Base>
     */
    public static function get($name)
    {
        // 获取配置
        $conf = Com::glob('com.connections');
        if (!isset($conf['dsn'][$name])) {
            throw new Exception_Kernel('Connection dsn is not found');
        }
        $conf = $conf['dsn'][$name];

        if (!isset(self::$connections[$name])) {
            $classname = 'Connection_'.$conf['class'];

            self::$connections[$name] = new $classname($conf);
        }

        return self::$connections[$name];
    }

    /**
     * 获取DSN组中的随机值
     * @param <string> $group
     * @return <string>
     */
    public static function getNameInGroup($group)
    {
        // 获取配置
        $conf = Com::glob('com.connections');
        if (!isset($conf['group'][$name])) {
            throw new Exception_Kernel('Connection group is not found');
        }
        $conf = $conf['group'][$name];
        return array_rand($conf);
    }

    /**
     * 关闭连接
     * @param <string> $name
     */
    public static function close($name = null)
    {
        if ($name) {
            self::$connections[$name]->close();
        } else {
            foreach (self::$connections as $name => $connection) {
                $connection->close();
            }
        }
    }
}
